package com.andy.customerService.service.impl;

import com.andy.customerService.entity.User;
import com.andy.customerService.entity.UserRole;
import com.andy.customerService.enums.ExceptionEnum;
import com.andy.customerService.exception.BusinessException;
import com.andy.customerService.mapper.UserRoleMapper;
import com.andy.customerService.pojo.request.UserRoleRequest;
import com.andy.customerService.service.UserRoleService;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 用户角色表 服务实现类
 * </p>
 *
 * @author Andy
 * @since 2021-12-27
 */
@Service
@Slf4j
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    @Autowired
    private UserRoleMapper userRoleMapper;


    /**
     * 批量添加角色
     *
     * @param userRoleRequest
     */
    @Transactional
    @Override
    public void addUserRole(UserRoleRequest userRoleRequest) {
        log.info("批量添加用户角色 入参：{}", userRoleRequest);
        if (null == userRoleRequest.getRoleId()) {
            throw new BusinessException(ExceptionEnum.ROLE_ID_CAN_NOT_BE_NULL);
        }
        UserRole userRole = new UserRole();
        //获取角色信息
        BeanUtils.copyProperties(userRoleRequest, userRole);
        //获取用户列表
        List<User> userList = userRoleRequest.getUserList();
        if (CollectionUtils.isNotEmpty(userList)) {
            for (User user : userList) {
                if (null == user.getId()) {
                    throw new BusinessException(ExceptionEnum.USER_ID_CAN_NOT_BE_NULL);
                }
                //获取用户信息
                BeanUtils.copyProperties(user, userRole);
            }
            userRole.setStatus("1");
            //插入用户角色关系表
            userRoleMapper.insert(userRole);
        }

    }

}
